package com.central.apps.handler.cronTask;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.central.app.service.HandlerService;
import com.central.apps.service.AppCustomService;
import com.central.common.util.ToolUtil;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * birt报表生成pdf定时任务
 */
@Component
@Configuration
@EnableScheduling
@CommonsLog
public class BirtPdfTimeTask {

    @Autowired
    private HandlerService handlerService;

    //birt报表生成pdf
    //格式: 秒 分 时 日 月 星期 年
    @Scheduled(cron="0 0 3 * * ?")
    public void birtPdfTimeTask() throws Exception {
        log.info("---------------------birtpdf-----------------");
        //获取所有数据
        List<Map<String, Object>> datas = handlerService.findBySql("select id,nextdate,reportfile,frequency,cycle from bl_autoexportreport");
        if(datas!=null&&datas.size()>0){
            for(Map<String, Object> data:datas){
                if(data==null||data.size()==0){
                    continue;
                }
                //获取基本信息
                String id = MapUtil.getStr(data, "id");
                Date nextdate = MapUtil.getDate(data, "nextdate");
                String reportfile = MapUtil.getStr(data, "reportfile");
                String frequency = MapUtil.getStr(data, "frequency");
                String cycle = MapUtil.getStr(data, "cycle");
                //如果报表文件空或者没有下一次执行时间 ，不做处理
                if(ToolUtil.isEmpty(reportfile)||nextdate==null){
                    continue;
                }
                log.info("--------------------------------------id："+id);
                log.info("--------------------------------------nextdate："+nextdate);
                log.info("--------------------------------------reportfile："+reportfile);
                log.info("--------------------------------------frequency："+frequency);
                log.info("--------------------------------------cycle："+cycle);
                //如果不是birt报表不处理
                if(!reportfile.toLowerCase().endsWith("rptdesign")){
                    continue;
                }
                //获取birt报表配置有默认值的参数
                Map<String, Object> params = CollUtil.newHashMap();
                List<Map<String, Object>> paramList = handlerService.findBySql("select srp.param as param, srp.default_val as pvalue from sys_report sr join sys_report_param srp  on sr.id = srp.report_id where sr.file='"+reportfile+"' and srp.default_val!=''");
                if(paramList!=null&&paramList.size()>0){
                    for(Map<String, Object> paramMap:paramList){
                        if(paramMap!=null&&paramMap.size()>0){
                            //添加报表参数
                            String param = MapUtil.getStr(paramMap, "param");
                            String pvalue = MapUtil.getStr(paramMap, "pvalue");
                            if(ToolUtil.isNotEmpty(param)&&ToolUtil.isNotEmpty(pvalue)){
                                params.put(param, pvalue);
                            }
                        }
                    }
                }
                //生成birt报表的pdf文件
                handlerService.createLocalBirtPdf("autoexportreportApp", reportfile, "", params);
                //生成下一次执行时间
                String upDateNextDate = getNextexDate(nextdate,frequency,cycle);
                String updateNextTimeSqlStr = "update bl_autoexportreport set nextdate=str_to_date('"+upDateNextDate+"', '%Y-%m-%d %H:%i:%s') where id="+id;
                //如果下一次执行时间是空，则将下一次执行时间更新为空。
                if(ToolUtil.isEmpty(upDateNextDate)){
                    updateNextTimeSqlStr = "update bl_autoexportreport set nextdate=null where id="+id;
                }
                log.info("--------------------------------------updateNextTimeSqlStr："+updateNextTimeSqlStr);
                //变更下一次执行时间
                handlerService.updateBySql(updateNextTimeSqlStr);
            }
        }
    }

    public String getNextexDate(Date exDate, String frequency, String cycle){
        int fre = Integer.parseInt(frequency);
        int unitTime = 0;
        if("D".equals(cycle)){
            unitTime = 1;
        }
        if("W".equals(cycle)){
            unitTime = 7;
        }
        if("M".equals(cycle)){
            unitTime = 30;
        }
        Calendar ca = Calendar.getInstance();
        ca.setTime(exDate);
        ca.add(Calendar.DAY_OF_MONTH, fre*unitTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(ca.getTime());
    }

}